const app = getApp()


Page({
  /**
   * 页面的初始数据
   */
  data: {
    receiverText: '',
    receiverLength: 0,
    sendText: '',
    sendLength: 0,
    time: 1000,
    timeSend: false,
  },
  /**
   * 自定义数据
   */
  customData: {
    sendText: '',
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    canWrite: false,
    canRead: false,
    canNotify: false,
    canIndicate: false,
    time: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this
    this.customData.deviceId = options.deviceId
    this.customData.serviceId = options.serviceId
    this.customData.characteristicId = options.characteristicId
    this.customData.canWrite = options.write === 'true' ? true : false
    this.customData.canRead = options.read === 'true' ? true : false
    this.customData.canNotify = options.notify === 'true' ? true : false
    this.customData.canIndicate = options.indicate === 'true' ? true : false
    /**
     * 如果支持notify
     */
    if (options.notify) {
      wx.notifyBLECharacteristicValueChange({
        deviceId: options.deviceId,
        serviceId: options.serviceId,
        characteristicId: options.characteristicId,
        state: true,
        success: function(res) {
          // do something...
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const self = this;
    function buf2string(buffer) {
      var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
      return arr.map((char, i) => {
        console.log(String.fromCharCode(char))
        return String.fromCharCode(char);
      }).join('');
    }
    /**
     * @Desc 获取到数据进行解码
     * @Content 首先判断是否为完整帧,如是下一步进行判断是否类似BB01FF...7E,如是则返回未获取到tag,
     *          否则又判断str是否超过24位,如是则从下坐标24位开始获取,长度为(str转化为10进制[下坐                 标第9*16+第10截取][注意此时要做判断是否数组越界])
     */
    function requestUrlById(str) {
      console.log("requestUrlById方法")
      console.log(str)
      //判断str是否存在
      //str = "BB01213sdasa7E"
      var objRegExp = /^(BB|bb)\w+(7E|7e)$/;
      if ( "undefined" != str ){
        //判断str是否符合完整帧["BB....7E"]
        if (objRegExp.test(str) ){
           if ( str.length >= 24){
             let tempStr = (str.substr(9, 1)*2 + str.substr(10, 1))*2-10;
             console.log(tempStr)
             if (str.length >= Number(24) + Number(tempStr) ){
                let sucStr = str.substr(24,tempStr);
                console.log(sucStr);
             }
          }else{
               wx.showToast({
                 title: '未获取到TAG标签,请重新请求!',
                 icon: 'success',
                 duration: 2000
             })
          }
        }else{
            wx.showToast({
              title: '数据有误,请重新请求!',
              icon: 'success',
              duration: 2000
            })
          }
      }else{
        wx.showToast({
          title: '未接受到数据!',
          icon: 'success',
          duration: 2000
        })
      }
      setTimeout(function () {
        wx.hideToast()
      }, 2000)
    }

    /**
     * 监听蓝牙设备的特征值变化
     */
    wx.onBLECharacteristicValueChange(function (res) {
      console.log("读取数据------")
      const tempText = app.buf2hex(res.value);
      const receiverText = app.hexCharCodeToStr(tempText);
      console.log(tempText)
     
      self.setData({
        receiverLength: self.data.receiverLength + receiverText.length
      })
      setTimeout(() => {
        self.setData({
          receiverText: (self.data.receiverText + receiverText).substr(-4000, 4000)
        })
      }, 200)
      console.log(receiverText)
      requestUrlById(receiverText);
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      receiverText: '',
      receiverLength: 0,
      sendText: '',
      sendLength: 0,
      time: 1000,
      timeSend: false
    })
  },
  /**
   * 更新发送框内容
   */
  updateSendText: function(event) {
    const value = event.detail.value
    this.customData.sendText = value
    this.setData({
      sendText: value
    })
  },
  /**
   * 更新定时发送时间间隔
   */
  updateTime: function(event) {
    const self = this
    const value = event.detail.value
    this.setData({
      time: /^[1-9]+.?[0-9]*$/.test(value) ? +value : 1000
    })
    clearInterval(this.customData.time)
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    this.customData.time = setInterval(() => {
      const sendText = self.customData.sendText
      const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
      if (app.globalData.connectState) {
        if (self.customData.canWrite) { // 可写
          self.writeData({ deviceId, serviceId, characteristicId, sendPackage })
        }
      }
    }, self.data.time)
  },
  /**
   * 清除接收
   */
  clearReceiverText: function(event) {
    // this.customData.receiverText = ''
    this.setData({
      receiverText: '',
      receiverLength: 0,
      sendLength: 0
    })
  },
  /**
   * 清除发送
   */
  clearSendText: function(event) {
    this.customData.sendText = ''
    this.setData({
      sendText: '',
      sendLength: 0
    })
  },
  /**
   * 手动发送
   */
  manualSend: function(event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    const sendText = this.customData.sendText
    const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        console.log("手动发送可写sendPackage:" + JSON.stringify(sendPackage) + "sendText:"+sendText)
        this.writeData({ deviceId, serviceId, characteristicId, sendPackage })
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
   * 查询版本
   */
  manualSendByVersion: function (event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    const sendText = 'BB0003000100047E'
    const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        console.log("手动发送可写sendPackage:" + JSON.stringify(sendPackage) + "sendText:" + sendText)
        this.writeData({ deviceId, serviceId, characteristicId, sendPackage })
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
   * 单次轮询指令
   */
  manualSendByOnlyPoll: function (event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    const sendText = 'BB00220000227E'
    const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        console.log("手动发送可写sendPackage:" + JSON.stringify(sendPackage) + "sendText:" + sendText)
        this.writeData({ deviceId, serviceId, characteristicId, sendPackage })
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
   * 多次轮询指令
   */
  manualSendByPoll: function (event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    const sendText = 'BB00270003222710837E'
    const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        console.log("手动发送可写sendPackage:" + JSON.stringify(sendPackage) + "sendText:" + sendText)
        this.writeData({ deviceId, serviceId, characteristicId, sendPackage })
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
  * 停止多次轮询指令
  */
  manualSendByStopPoll: function (event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    const sendText = 'BB00280000287E'
    const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        console.log("手动发送可写sendPackage:" + JSON.stringify(sendPackage) + "sendText:" + sendText)
        this.writeData({ deviceId, serviceId, characteristicId, sendPackage })
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
  * 控制IO端口
  */
  manualSendByIO: function (event) {
    const deviceId = this.customData.deviceId // 设备ID
    const serviceId = this.customData.serviceId // 服务ID
    const characteristicId = this.customData.characteristicId // 特征值ID
    const sendText = 'BB001A0003000401227E' 
    const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
    if (app.globalData.connectState) {
      if (this.customData.canWrite) { // 可写
        console.log("手动发送可写sendPackage:" + JSON.stringify(sendPackage) + "sendText:" + sendText)
        this.writeData({ deviceId, serviceId, characteristicId, sendPackage })
      }
    } else {
      wx.showToast({
        title: '已断开连接',
        icon: 'none'
      })
    }
  },
  /**
   * 自动发送
   */
  timeChange (event) {
    this.setData({
      timeSend: event.detail.value.length ? true : false
    })
    if (!this.data.timeSend) {
      clearInterval(this.customData.time)
    } else {
      const self = this
      const deviceId = this.customData.deviceId // 设备ID
      const serviceId = this.customData.serviceId // 服务ID
      const characteristicId = this.customData.characteristicId // 特征值ID
      this.customData.time = setInterval(() => {
        const sendText = self.customData.sendText
        const sendPackage = app.subPackage(sendText) // 数据分每20个字节一个数据包数组
        if (app.globalData.connectState) {
          if (self.customData.canWrite) { // 可写
            self.writeData({ deviceId, serviceId, characteristicId, sendPackage })
          }
        }
      }, self.data.time)
    }
  },
  /**
   * 向特征值写数据(write)
   */
  writeData: function ({deviceId, serviceId, characteristicId, sendPackage, index = 0}) {
    const self = this
    let i = index;
    let len = sendPackage.length;
    if (len && len > i) {
      console.log("发送正在进行中:deviceId" + deviceId + "serviceId:" + serviceId + "characteristicId:" + characteristicId + "sendPackage:" + sendPackage + "index:" + index + "len:" + len)
      // 向蓝牙设备发送一个0x00的16进制数据
      //let testStr = "BB0003000100047E";
      wx.writeBLECharacteristicValue({
        deviceId,
        serviceId,
        characteristicId,
        value: app.string2bufTest(sendPackage[i]),
        success: function (res) {
          console.log("发送成功!app.string2bufTest(sendPackage[i])" + app.string2bufTest(sendPackage[i]) + "数组" + sendPackage[i])
          console.log(app.string2bufTest(sendPackage[i]))
          console.log(JSON.stringify(res))
          self.setData({
            sendLength: self.data.sendLength + sendPackage[i].length // 更新已发送字节数
          })
          i += 1;
          self.writeData({deviceId, serviceId, characteristicId, sendPackage, index: i}) // 发送成功，发送下一个数据包
        },
        fail: function (res) {
          self.writeData({deviceId, serviceId, characteristicId, sendPackage, index}) // 发送失败，重新发送
        }
      })
    }
  }
})